// 认证路由
const express = require('express');
const router = express.Router();
const { query } = require('../config/database');
const { hashPassword, comparePassword, generateToken } = require('../utils/helpers');
const { validateRegister, validateLogin } = require('../middleware/validation');
const { authenticateToken } = require('../middleware/auth');
const ResponseHelper = require('../utils/response');

// 用户注册
router.post('/register', validateRegister, async (req, res) => {
  try {
    const { username, phone, password, email, real_name } = req.body;

    // 检查用户名和手机号是否已存在
    const existingUsers = await query(
      'SELECT id FROM users WHERE username = ? OR phone = ?',
      [username, phone]
    );

    if (existingUsers.length > 0) {
      return ResponseHelper.error(res, '用户名或手机号已存在', 400);
    }

    // 加密密码
    const hashedPassword = await hashPassword(password);

    // 创建新用户
    const result = await query(
      `INSERT INTO users (username, phone, password, email, real_name, role, status, balance, play_time, created_at) 
       VALUES (?, ?, ?, ?, ?, 'user', 'active', 0.00, 0, NOW())`,
      [username, phone, hashedPassword, email || '', real_name || '']
    );

    // 生成JWT token
    const token = generateToken(result.insertId, 'user');

    // 返回用户信息（不包含密码）
    const userData = {
      id: result.insertId,
      username,
      phone,
      email: email || '',
      real_name: real_name || '',
      role: 'user',
      status: 'active',
      balance: '0.00',
      play_time: 0
    };

    ResponseHelper.success(res, {
      token,
      user: userData
    }, '注册成功', 201);

  } catch (error) {
    console.error('用户注册错误:', error);
    ResponseHelper.serverError(res, '注册失败，请稍后重试');
  }
});

// 用户登录
router.post('/login', validateLogin, async (req, res) => {
  try {
    const { phone, password } = req.body;

    // 查找用户
    const users = await query(
      'SELECT id, username, phone, password, email, real_name, role, status, balance, play_time, avatar, created_at FROM users WHERE phone = ?',
      [phone]
    );

    if (users.length === 0) {
      return ResponseHelper.error(res, '手机号或密码错误', 401);
    }

    const user = users[0];

    // 检查用户状态
    if (user.status !== 'active') {
      return ResponseHelper.error(res, '账户已被禁用，请联系管理员', 401);
    }

    // 验证密码
    const isPasswordValid = await comparePassword(password, user.password);
    if (!isPasswordValid) {
      return ResponseHelper.error(res, '手机号或密码错误', 401);
    }

    // 生成JWT token
    const token = generateToken(user.id, user.role);

    // 返回用户信息（不包含密码）
    const userData = {
      id: user.id,
      username: user.username,
      phone: user.phone,
      email: user.email,
      real_name: user.real_name,
      role: user.role,
      status: user.status,
      balance: user.balance,
      play_time: user.play_time,
      avatar: user.avatar,
      created_at: user.created_at
    };

    ResponseHelper.success(res, {
      token,
      user: userData
    }, '登录成功');

  } catch (error) {
    console.error('用户登录错误:', error);
    ResponseHelper.serverError(res, '登录失败，请稍后重试');
  }
});

// 获取当前用户信息
router.get('/me', authenticateToken, async (req, res) => {
  try {
    const user = req.user;

    // 返回用户信息
    const userData = {
      id: user.id,
      username: user.username,
      phone: user.phone,
      email: user.email,
      real_name: user.real_name,
      role: user.role,
      status: user.status,
      balance: user.balance,
      play_time: user.play_time,
      avatar: user.avatar,
      created_at: user.created_at
    };

    ResponseHelper.success(res, { user: userData }, '获取用户信息成功');

  } catch (error) {
    console.error('获取用户信息错误:', error);
    ResponseHelper.serverError(res, '获取用户信息失败');
  }
});

// 刷新token
router.post('/refresh', authenticateToken, async (req, res) => {
  try {
    const user = req.user;

    // 生成新的token
    const newToken = generateToken(user.id, user.role);

    ResponseHelper.success(res, {
      token: newToken
    }, 'Token刷新成功');

  } catch (error) {
    console.error('Token刷新错误:', error);
    ResponseHelper.serverError(res, 'Token刷新失败');
  }
});

// 用户登出（客户端处理，服务端记录日志）
router.post('/logout', authenticateToken, async (req, res) => {
  try {
    // 这里可以添加登出日志记录
    console.log(`用户 ${req.user.username} (ID: ${req.user.id}) 已登出`);

    ResponseHelper.success(res, null, '登出成功');

  } catch (error) {
    console.error('用户登出错误:', error);
    ResponseHelper.serverError(res, '登出失败');
  }
});

module.exports = router;
